package handler.wx

import org.apache.commons.codec.digest.DigestUtils

import service.wx.WxSignature
import service.wx.WxMessager
import service.wx.WxApi

handler.get('/wx/refresh'){req, resp ->
	WxSignature.refreshConf()
	resp.end 'ok'
}

// 公众号服务提供的接入验证
// refer http://mp.weixin.qq.com/wiki/17/2d4265491f12608cd170a95559800f2d.html
handler.get('/wx/token'){req, resp ->
	String s = req.params.signature
	String t = req.params.timestamp
	String n = req.params.nonce

	String echostr = req.params.echostr

	final String token = 'whatever'

	List ll = [token, t, n]
	ll.sort()

	String str = ll.join('')
	str = DigestUtils.shaHex(str)

	boolean isCheckOk = s == str
	if(isCheckOk)
		resp.end echostr
	else
		resp.end 'fail'
}

// 公众号服务普通消息的dispatcher
// refer http://mp.weixin.qq.com/wiki/10/79502792eef98d6e0c6e1739da387346.html
handler.post('/wx/token'){req, resp ->
	// 接收xml
	req.bodyHandler{body -> 
		final String encoding  = 'utf-8'
		XmlParser parser = new XmlParser()

		try{
		// *** try begin
   
		// 解析xml
		def root = parser.parseText(new String(body.bytes, encoding))

		Map<String, String> info = [:]
		info.ToUserName = root.ToUserName.text()
		info.FromUserName = root.FromUserName.text()
		info.CreateTime = root.CreateTime.text()

		info.MsgType = root.MsgType.text()
		info.MsgId = root.MsgId.text()

		if('text' == info.MsgType){
			info.Content = root.Content.text()
		}else if('image' == info.MsgType){
			info.PicUrl = root.PicUrl.text()
			info.MediaId = root.MediaId.text()
		}else if('voice' == info.MsgType){
			info.Format = root.Format.text()
		}else if('video' == info.MsgType){
			info.ThumbMediaId = root.ThumbMediaId.text()
		}else if('location' == info.MsgType){
			info.Location_X = root.Location_X.text()
			info.Location_Y = root.Location_Y.text()
			info.Scale = root.Scale.text()
			info.Label = root.Label.text()
		}else if('link' == info.MsgType){
			info.Title = root.Title.text()
			info.Description = root.Description.text()
			info.Url = root.Url.text()
		}else if('event' == info.MsgType){
			info.Event = root.Event.text()
			info.EventKey = root.EventKey.text()
		}else{
		}

		log.info('wx info : ' + info)

		// command模式，处理信息
		Map<String, String> result = WxMessager.inst.process(info)
		if(!result){
			resp.end ''
			return
		}
		// 返回给发送者，调换openid
		result.ToUserName = info.FromUserName
		result.FromUserName = info.ToUserName

		// 返回xml
		def sw = new StringWriter()
		def builder = new groovy.xml.MarkupBuilder(sw)
		String[] keys = ['ToUserName', 'FromUserName', 'MsgType', 
			'Content', 'PicUrl', 'Location_X', 'Location_Y', ,'Scale', 'Label', 
			'Title', 'Description', 'Url']
		builder.xml{
			CreateTime('' + new Date().getTime())

			for(key in keys){
				if(result[key]){
			"${key}"(result[key])
				}
			}
		}
		resp.end(sw.toString())

		// *** try end
		}catch(ex){
			log.error('wx info error!', ex)
			resp.end ''
		}
	}
}

handler.get('/wx/create-menu'){req, resp ->
	def menu = [
		button: [
			[
				type: 'click', 
				name: '我要打卡', 
				key: 'toScan'
			],	
			[
				type: 'click', 
				name: '查询记录', 
				key: 'queryScanHistory'
			],	
			[
				name: '管理', 
				sub_button: [
					[
						type: 'click', 
						name: '显示二维码', 
						key: 'showScaner'
					],	
					[
						type: 'click', 
						name: '会议列表', 
						key: 'showMeeting'
					],	
					[
						type: 'click', 
						name: '打卡统计', 
						key: 'stat'
					],
					[
						type: 'view', 
						name: '意见反馈', 
						url: 'http://dy126.net/public/ibid/leave-msg.html'
					]
				]
			]	
		]
	]
	def r = WxApi.createMenu(menu)
	resp.json r
}